package com.itshen.one.controller;

import com.itshen.entity.User;
import com.itshen.repository.UserRepository;
import com.itshen.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserRepository repository;

    /**
     * 以数组形式一次性返回数据
     *
     * @return
     */
    @GetMapping
    public Flux<User> getAll() {
        return repository.findAll();
    }

    /**
     * 以SSE形式多次返回数据
     *
     * @return
     */
    @GetMapping(value = "/stream", produces  = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getAllFromStream() {
        return repository.findAll();
    }

    /**
     * 新增
     *
     * @param user
     * @return
     */
    @PostMapping
    public Mono<User> create(@Validated @RequestBody User user) {
        CheckUtil.checkName(user.getName());
        // jpa的新增和修改都是save方法，有id是修改，无id是新增
        user.setId(null);
        return repository.save(user);
    }

    /**
     * 根据id删除用户 存在的时候返回200, 不存在返回404
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Void>> delete(@PathVariable String id) {
        return repository.findById(id)
                // 操作数据 User -> Mono
                .flatMap(user -> repository.delete(user)
                        .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 修改数据 存在的时候返回200 和修改后的数据, 不存在的时候返回404
     *
     * @param id
     * @param user
     * @return
     */
    @PutMapping("/{id}")
    public Mono<ResponseEntity<User>> update(@PathVariable String id,@Validated @RequestBody User user) {
        CheckUtil.checkName(user.getName());
        return repository.findById(id)
                // 操作数据, 并返回一个Mono
                .flatMap(u -> {
                    u.setAge(user.getAge());
                    u.setName(user.getName());
                    return repository.save(u);
                })
                // 不操作数据, 只是转换数据
                .map(u -> new ResponseEntity<User>(HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据ID查找用户 存在返回用户信息, 不存在返回404
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Mono<ResponseEntity<User>> find(@PathVariable String id) {
        return repository.findById(id)
                .map(u -> new ResponseEntity<>(u, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }


    /**
     * 根据年龄查找用户
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/age/{start}/{end}")
    public Flux<User> findByAge(@PathVariable("start") int start,
                                @PathVariable("end") int end){
        return repository.findByAgeBetween(start,end);
    }

    /**
     * 根据年龄查找用户
     *
     * @param start
     * @param end
     * @return
     */
    @GetMapping(value = "/stream/age/{start}/{end}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> streamFindByAge(@PathVariable("start") int start,
                                      @PathVariable("end") int end) {
        return this.repository.findByAgeBetween(start, end);
    }

    /**
     *  得到20-30用户
     * @return
     */
    @GetMapping("/old")
    public Flux<User> oldUser() {
        return this.repository.oldUser();
    }

    /**
     * 得到20-30用户
     *
     * @return
     */
    @GetMapping(value = "/stream/old", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> streamOldUser() {
        return this.repository.oldUser();
    }
}
